#pragma once

#include <QString>
#include <QSqlDatabase>
#include <QMutex>
#include <QWaitCondition>
#include <memory>
#include <queue>
#include <QDebug>
#include <QFile>
#include "../nlohmann/json.hpp"

using json = nlohmann::json;

class DatabaseUtil {
public:
    static DatabaseUtil &getInstance();

    bool init(const QString &configPath);

    QSqlDatabase getConnection();

    void releaseConnection(QSqlDatabase conn);

    json executeQuery(const QString &query, const QVariantList &params = {});

    int executeUpdate(const QString &query, const QVariantList &params = {});

private:
    DatabaseUtil() = default;

    ~DatabaseUtil();

    DatabaseUtil(const DatabaseUtil &) = delete;

    DatabaseUtil &operator=(const DatabaseUtil &) = delete;

    bool loadConfig(const QString &path);

    void initPool(int poolSize = 10);

    json configJson;
    QString connectionNamePrefix = "conn_";
    QString host, user, password, database;
    int port = 3306;
    int connectionCounter = 0;

    std::queue<QString> connectionPool;
    QMutex poolMutex;
    QWaitCondition poolCond;
};
